﻿#region License
// Copyright 2010 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MediaWiki.Common;
using MediaWiki.MediaWikiConverter.Utilities;
using Microsoft.Office.Core;
using System.EnterpriseServices;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using MediaWiki.MediaWikiConverter.UI;
using MediaWiki.MediaWikiConverter.Utilities.Logging;
using MediaWiki.MediaWikiConverter.Utilities.Logging.Writers;
using MediaWiki.MediaWikiConverter.Exporter;
using MediaWiki.MediaWikiConverter.Utilities.Logging.Filters;
using System.IO;

namespace MediaWiki.MediaWikiConverter
{
  [ComVisible(true)]
  [Guid("34E1E1C1-096D-4150-911F-429B6019DB94")]
  public class MediaWikiConverter : ServicedComponent, IConverter
  {
    private static readonly object _lock = new object();
    private static bool _initialized;

    private void Initialize()
    {
      if (!_initialized)
      {
        lock (_lock)
        {
          if (!_initialized)
          {
            // setup logging to log warnings and above to the event log
            Logger.SuppressErrors = false;
            Logger.Loggers.Add(new LogInstance
              {
                LogWriter = new EventLogWriter(Constants.ApplicationName),
                LogFilters = { new LogLevelFilter(LogLevel.Warning) }
              });
            _initialized = true;

            Logger.Info("MediaWikiConverter initialized");
          }
        }
      }
    }

    public void HrExport(string bstrSourcePath, string bstrDestPath, string bstrClass, IConverterApplicationPreferences pcap, out IConverterPreferences ppcp, IConverterUICallback pcuic)
    {
      Initialize();
      ppcp = new MediaWikiConverterPreferences();

      Logger.Info("bstrSourcePath: {0}, bstrDestPath: {1}, bstrClass: {2}".FormatWith(bstrSourcePath, bstrDestPath, bstrClass));

      Logger.Trace("Exporting MediaWiki", () =>
        {
          ExportMediaWiki(bstrSourcePath, bstrDestPath);

          //// example of launching an options window during export

          //int hwnd;
          //pcap.HrGetHwnd(out hwnd);

          //IntPtr handle = (IntPtr) hwnd;
          //HostWindow hostWindow = new HostWindow(handle);

          //using (ExportOptionsForm exportOptionsForm = new ExportOptionsForm())
          //{
          //  DialogResult result = exportOptionsForm.ShowDialog(hostWindow);
          //  Logger.Verbose("Options dialog result: " + result);

          //  if (result == DialogResult.OK)
          //  {
          //    ExportMediaWiki(bstrSourcePath, bstrDestPath);
          //  }
          //}
        });
    }

    private void ExportMediaWiki(string sourceOpenXmlDocumentPath, string newMediaWikiDocumentPath)
    {
      using (Stream source = File.OpenRead(sourceOpenXmlDocumentPath))
      using (Stream destination = File.Create(newMediaWikiDocumentPath))
      {
        MediaWikiExporter exporter = new MediaWikiExporter(source, destination);
        // output mediawiki text file as UFT8 without BOM
        exporter.OutputEncoding = new UTF8Encoding(false);

        exporter.Export();
      }
    }

    public void HrGetErrorString(int hrErr, out string pbstrErrorMsg, IConverterApplicationPreferences pcap)
    {
      pbstrErrorMsg = null;
    }

    public void HrGetFormat(string bstrPath, out string pbstrClass, IConverterApplicationPreferences pcap, out IConverterPreferences ppcp, IConverterUICallback pcuic)
    {
      pbstrClass = "MediaWikiConverter";
      ppcp = new MediaWikiConverterPreferences();
    }

    public void HrImport(string bstrSourcePath, string bstrDestPath, IConverterApplicationPreferences pcap, out IConverterPreferences ppcp, IConverterUICallback pcuic)
    {
      Initialize();

      ppcp = new MediaWikiConverterPreferences();
    }

    public void HrInitConverter(IConverterApplicationPreferences pcap, out IConverterPreferences ppcp, IConverterUICallback pcuic)
    {
      ppcp = new MediaWikiConverterPreferences();
    }

    public void HrUninitConverter(IConverterUICallback pcuic)
    {
    }
  }
}